<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button size="small" type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['safety:position:export']">导出</el-button>
      </el-col>
      <TabRightBar :columns="columns" :filterSelected="filterSelected" @queryTable="getList" @sure="saveFields" />
    </el-row>

    <el-table class="tabs-table" ref="multipleTable" :height="height + 'px'" highlight-current-row border stripe
      :data="positionList" @selection-change="handleSelectionChange" @row-contextmenu="nodeContextmenu"
      @row-dblclick="showInfo">
      <el-table-column fixed type="selection" width="55" align="center" />
      <el-table-column fixed type="index" width="60" align="center" label="序号" />
      <el-table-column fixed label="车牌号" width="100" sortable align="center" prop="plateNo" />
      <template v-for="(item, index) in showColumns">
        <el-table-column :label="item.label" sortable align="center" :prop="item.field" :show-overflow-tooltip="true"
          :width="_field_columns(item.field, 'field').width + 'px'">
          <template v-if="item.field == 'longitude'" #default="scope">
            <span>{{ scope.row.longitude }},{{ scope.row.latitude }}</span>
          </template>
          <template v-if="item.field == 'color'" #default="scope">
            <dict-tag :options="basic_vehicle_color" :value="scope.row.color" />
          </template>
          <template v-if="item.field == 'outageStatus'" #default="scope">
            <dict-tag :options="basic_vehicle_outage_status" :value="scope.row.outageStatus" />
          </template>
          <template v-if="item.field == 'direction'" #default="scope">
            {{ toDirStr(scope.row.direction) }}
          </template>
          <template v-if="item.field == 'state'" #default="scope">
            {{ accStatus(scope.row.state) }}
          </template>
          <template v-if="item.field == 'mileage'" #default="scope">
            {{ kmUnit(scope.row.mileage) }}km
          </template>
        </el-table-column>
      </template>
      <!-- <el-table-column label="所属机构" sortable align="center" prop="deptName" :width="_field_columns(item.field, 'field').width"  />
      <el-table-column label="定位时间" sortable align="center" prop="times" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.times, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回传时间" sortable align="center" prop="onlineTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.onlineTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="位置" sortable align="center" prop="location" />
      <el-table-column label="GPS速度" sortable align="center" prop="satelliteCount" />
      <el-table-column label="限速值" sortable align="center" prop="limitSpeed" />
      <el-table-column label="acc状态" sortable align="center" prop="state" />
      <el-table-column label="SIM卡号" sortable align="center" prop="msisdn" />
      <el-table-column label="海拔" sortable align="center" prop="height" /> -->
    </el-table>
    <v-contextmenu ref="contextmenu" theme="bright">
      <v-contextmenu-item>设置停运状态</v-contextmenu-item>
      <v-contextmenu-item>轨迹跟踪</v-contextmenu-item>
      <v-contextmenu-item>实时视频</v-contextmenu-item>
      <v-contextmenu-item>视频回放</v-contextmenu-item>
      <v-contextmenu-item>轨迹回放</v-contextmenu-item>
      <v-contextmenu-item>短信下发</v-contextmenu-item>
      <v-contextmenu-item>语音对讲</v-contextmenu-item>
      <v-contextmenu-item>拍摄照片</v-contextmenu-item>
      <v-contextmenu-item>终端信息读取</v-contextmenu-item>
    </v-contextmenu>
  </div>
</template>

<script setup name="Position">
import TabRightBar from "@/components/TabRightToolbar"
import { listPosition, getPosition, delPosition, } from "@/api/safety/position";
import { toDirStr, kmUnit, accStatus } from '@/utils/utils.js'
import useSatetyMapStore from '@/store/modules/safetyMap'
import { detaildPageSetting, addPageSetting, updatePageSetting } from '@/api/basic/userPageSetting.js'
const { proxy } = getCurrentInstance();
const { basic_vehicle_color, basic_vehicle_outage_status } = proxy.useDict('basic_vehicle_color', 'basic_vehicle_outage_status');
const safeMapStore = useSatetyMapStore();
const positionList = ref([]);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const ConfigSetting = ref({})
const showColumns = ref([])
const filterSelected = ref([])
var configKey = 'positionTable';

async function getConfig() {
  let config = await detaildPageSetting(configKey)
  if (config.data != null) {
    showColumns.value = JSON.parse(config.data.content)
    ConfigSetting.value = config.data
  }
  else {
    showColumns.value = JSON.parse(JSON.stringify(defaultColumns.value))
  }
  filterSelected.value = _getFilterSelected(showColumns.value);
}
getConfig()
function _getFilterSelected(arr = []) {
  return arr.map((item) => {
    return item.key;
  })
}
/**
 * 保存字段
 * @param {*} datas 
 */
function saveFields(datas) {
  console.log('selected', datas);
  let newColums = [];
  datas.forEach((element, index) => {
    newColums.push({
      key: element,
      label: _field_columns(element).label,
      field: _field_columns(element).field
    })
  });
  let parmas = {
    page: configKey,
    content: JSON.stringify(newColums)
  }
  if (typeof ConfigSetting.value.id == 'undefined') {
    addPageSetting(parmas).then(res => {
      proxy.$modal.msgSuccess("保存成功");
      showColumns.value = newColums
      getConfig()
    })
  } else {
    parmas.id = ConfigSetting.value.id;
    updatePageSetting(parmas).then(res => {
      proxy.$modal.msgSuccess("保存成功");
      showColumns.value = newColums
      getConfig()
    })
  }
}
var fieldColumns = {}
function _field_columns(key = '', findKey = 'key') {
  if (!fieldColumns.hasOwnProperty(findKey)) {
    fieldColumns[findKey] = {};
    columns.value.forEach((item) => {

      fieldColumns[findKey][findKey + '_' + item[findKey]] = item
    })
  }
  return fieldColumns[findKey][findKey + '_' + key] ? fieldColumns[findKey][findKey + '_' + key] : '';
}
const defaultColumns = ref([
  { key: 3, label: `机构`, visible: true, field: 'deptName' },
  { key: 20, label: `设备时间`, visible: true, field: 'times' },
  { key: 19, label: `GPS回传时间`, visible: true, field: 'onlineTime' },
  { key: 6, label: `位置`, visible: true, field: 'location' },
  { key: 9, label: `实时速度`, visible: true, field: 'speed' },
  { key: 8, label: `限速`, visible: true, field: 'limitSpeed' },
  { key: 12, label: `ACC状态`, visible: true, field: 'state' },
  { key: 18, label: `SIM卡号`, visible: true, field: 'msisdn' },
  { key: 21, label: `海拔`, visible: true, field: 'height' }
])
const columns = ref([
  { key: 0, label: `车牌颜色`, visible: true, field: 'color', width: 180 },
  { key: 1, label: `自编号`, visible: true, field: 'numbered', width: 180 },
  { key: 2, label: `司机`, visible: true, field: 'driverName', width: 180 },
  { key: 3, label: `机构`, visible: true, field: 'deptName', width: 180 },
  { key: 4, label: `线路`, visible: true, field: 'operationRoute', width: 180 },
  { key: 5, label: `车队`, visible: true, field: 'fleetName', width: 180 },
  { key: 6, label: `位置`, visible: true, field: 'location', width: 600 },
  { key: 7, label: `经纬度`, visible: true, field: 'longitude', width: 180 },
  { key: 8, label: `限速`, visible: true, field: 'limitSpeed', width: 180 },
  { key: 9, label: `实时速度`, visible: true, field: 'speed', width: 180 },
  { key: 10, label: `行车记录仪速度`, visible: true, field: 'meter', width: 180 },
  { key: 11, label: `司机卡号`, visible: true, field: 'driverId', width: 180 },
  { key: 12, label: `ACC状态`, visible: true, field: 'state', width: 180 },
  { key: 13, label: `方向`, visible: true, field: 'direction', width: 180 },
  { key: 14, label: `里程`, visible: true, field: 'mileage', width: 180 },
  { key: 15, label: `卫星数`, visible: true, field: 'satelliteCount', width: 180 },
  { key: 16, label: `信号强度`, visible: true, field: 'signalStrength', width: 180 },
  { key: 17, label: `设备号`, visible: true, field: 'deviceCode', width: 180 },
  { key: 18, label: `SIM卡号`, visible: true, field: 'msisdn', width: 180 },
  { key: 19, label: `GPS回传时间`, visible: true, field: 'onlineTime', width: 180 },
  { key: 20, label: `设备时间`, visible: true, field: 'times', width: 180 },
  { key: 21, label: `海拔`, visible: true, field: 'height', width: 180 },
  { key: 22, label: `驾驶员电话`, visible: true, field: 'driverTel', width: 180 },
  { key: 23, label: `SD卡状态`, visible: true, field: 'sdState', width: 260 },
  { key: 24, label: `摄像头状态`, visible: true, field: 'cameraState', width: 180 },
  { key: 25, label: `录像状态`, visible: true, field: 'videoState', width: 180 },
  { key: 36, label: `载重状态`, visible: true, field: 'loadState', width: 180 },
  { key: 27, label: `停运状态`, visible: true, field: 'outageStatus', width: 180 },
]);
const data = reactive({
  form: {},
  queryParams: [],
});

const { queryParams, form } = toRefs(data);

/** 查询实时位置列表 */
function getList() {
  loading.value = true;
  listPosition(queryParams.value).then(response => {
    // response.data = response.data == '' ? [] : response.data
    positionList.value = response.data;
    loading.value = false;
    safeMapStore.setSelectedVehicleDatas(response.data)
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.deviceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const defaultAllVehicleIds = computed(() => {
  return safeMapStore.defaultAllVehicleIds
})
/** 导出按钮操作 */
function handleExport() {
  let where = queryParams.value.length > 0 ? queryParams.value : defaultAllVehicleIds.value;
  proxy.download('safety/position/export', { ids: where }, `position_${new Date().getTime()}.xlsx`)
}

function showInfo(row, column, event) {
  console.log(row)
  // safeMapStore.setMapCenterLngLat(row.longitude,row.latitude)
  safeMapStore.setCurrentSelectVehicleId(row.vehicleId)
  safeMapStore.setTreeEjectHeight(259)
  safeMapStore.setZtreeHeight(480)
}

const selectedVehicleIds = computed(() => {
  return safeMapStore.selectedVehicleIds
})
const height = computed(() => {
  return safeMapStore.tabTableHeight
})

const currentSelectVehicleId = computed(() => {
  return safeMapStore.currentSelectVehicleId
})

//监听车辆树选中的车辆IDs
watch(selectedVehicleIds, (value) => {
  console.log('已选中车辆IDS', value)
  queryParams.value = value
  if (value.length == 0) {
    positionList.value = [];
    safeMapStore.setSelectedVehicleDatas([])
  } else {
    getList();
  }
}, {
  deep: true
})

watch(currentSelectVehicleId, (value) => {
  console.log('已选中车辆', value)
  // proxy.$refs['multipleTable'].setScrollTop(800)
  // multipleTable.value.setScrollTop(800)
  searchMember(value)
})
function setVehicleData(vehicldId = '') {
  for (let i in positionList.value) {
    if (positionList.value[i].vehicleId == vehicldId) {
      safeMapStore.setCurrentSelectVehicleData(positionList.value[i])
      break;
    }
  }
}
const multipleTable = ref();
function searchMember(vehicleId = '') {
  // 遍历表格数据，获取查询的数据
  let tableLength = positionList.value.length;
  if (positionList.value && tableLength > 0) {
    for (let i = 0; i < tableLength; i++) {
      let item = positionList.value[i];
      // 判断查询的数据是否存在，存在则进行定位操作
      if (item.vehicleId == vehicleId) {
        i = i < 1 ? 1 : i;
        let scrollTop = (29 * (i - 1))
        multipleTable.value.setScrollTop(scrollTop);
        multipleTable.value.setCurrentRow(item);
        break;
      }
    }
  }
}
function nodeContextmenu(row, column, event) {
  proxy.$refs['contextmenu'].show({ left: event.pageX, top: event.pageY })
  event.preventDefault()
}

//定时更新车辆定位数据
var timer = 0;
onMounted(() => {
  // console.log('position onMounted')
})
onUnmounted(() => {
  // console.log('position onUnmounted')
  clearInterval(timer); //清除定时器
  timer = 0;
})
onActivated(() => {
  // 调用时机为首次挂载
  // 以及每次从缓存中被重新插入时
  // console.log('position activeted')
  window.addEventListener('click', () => {
    // proxy.$refs['contextmenu'].hide()
  })
  timer = setInterval(() => {
    //设置定时器
    getList(); //自定义事件
  }, 60000);

})

onDeactivated(() => {
  // 在从 DOM 上移除、进入缓存
  // 以及组件卸载时调用
  console.log('position unactiveted')
  clearInterval(timer); //清除定时器
  timer = 0;
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 10px;

  :deep(.el-row) {
    align-items: center;
  }

  :deep(.el-table) {
    background-color: #091940;
    color: #FFFFFF;
  }

  :deep(.el-table__header th) {
    background-color: #1C2F61 !important;
    color: #FFFFFF;
    border-color: #4E5A75;
  }

  :deep(.el-table .el-table__cell) {
    border-right: 1px solid #4E5A75;
    border-bottom: 1px solid #4E5A75;
  }

  :deep(.el-table.is-scrolling-left.el-table--border .el-table-fixed-column--left.is-last-column.el-table__cell) {
    border-right: 1px solid #4E5A75;
  }

  :deep(.el-table__body tr.el-table__row > td) {
    background-color: #091940;
  }

  :deep(.el-table__body tr.el-table__row--striped > td),
  :deep(.el-table--striped .el-table__body tr.el-table__row--striped.current-row td.el-table__cell) {
    background-color: #0E204D;
  }

  :deep(.el-table__body tr.current-row >td),
  :deep(.el-table--striped .el-table__body tr.el-table__row--striped.current-row td.el-table__cell) {
    background-color: #1C2F61
  }

  :deep(.el-table__body tr.hover-row.current-row > td),
  :deep(.el-table__body tr.hover-row.el-table__row--striped.current-row > td),
  :deep(.el-table__body tr.hover-row.el-table__row--striped>td),
  :deep(.el-table__body tr.hover-row > td),
  :deep(.el-table--enable-row-hover .el-table__body tr:hover>td.el-table__cell) {
    background-color: #1C2F61;
  }
}
</style>
